package com.atguigui.leetcode1;

/**
 * 443. 压缩字符串
 * Project: leetcode
 * Package: com.atguigui.leetcode1
 * Version: 1.0
 * <p>
 * Created by WJX on 2023/7/12 10:32
 */
public class P443StringCompression {
    public static void main(String[] args) {
        Solution solution = new P443StringCompression().new Solution();
        char[] arr = {'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c'};
        System.out.println(solution.compress(arr));

    }

    class Solution {
        public int compress(char[] chars) {

            int n = chars.length;
            int i = 1;
            int ans = 0;
            char a = chars[0];
            int sum = 1;
            int b = 0;
            while (i <= n) {

                if (i == n) {
                    chars[b] = a;
                    b++;
                    String s = sum + "";
                    if (sum > 1) {
                        int l = s.length();
                        for (int j = 0; j < l; j++) {
                            chars[b + j] = s.charAt(j);
                        }
                        b += l;


                        ans += l + 1;
                    } else {
                        ans += 1;
                    }


                    break;
                }

                if (a == chars[i]) {
                    sum++;
                } else {
                    chars[b] = a;
                    b++;
                    String s = sum + "";
                    if (sum > 1) {
                        int l = s.length();
                        for (int j = 0; j < l; j++) {
                            chars[b + j] = s.charAt(j);
                        }
                        b += l;

                        ans += l + 1;
                    } else {
                        ans += 1;
                    }
                    a = chars[i];
                    sum = 1;
                }
                i++;
            }


            return ans;
        }
    }
}
